<template>
  <div class="app-container">
    <el-card shadow="hover">
      <div style="margin-bottom: 10px;">
        <i class="el-icon-search" />
        <span>筛选搜索</span>
      </div>
      <span>
        <el-autocomplete
          class="inline-input"
          v-model="queryParams.categoryName"
          :fetch-suggestions="querySearch"
          placeholder="请输入内容"
          value-key="categoryName"
          clearable
          @clear="fetchGoodsType"
        ></el-autocomplete>
      </span>
      <el-button
        class="btn-add"
        type="cyan"
        icon="el-icon-search"
        size="small"
        @click="fetchGoodsType"
      >
        搜索
      </el-button>
      <el-button
        class="btn-add"
        type="primary"
        icon="el-icon-plus"
        size="small"
        @click="handleAdd"
      >
        添加
      </el-button>
      <el-button
        type="danger"
        icon="el-icon-delete"
        class="handle-del mr10"
        size="small"
        :disabled="multiple"
        @click="handleDelete"
        >批量删除</el-button
      >
    </el-card>
    <div style="margin-top: 20px;">
      <!-- <el-card shadow="hover">
        <h4>证书分类管理</h4> -->
      <el-table
        v-loading="loading"
        :data="cateList"
        row-key="id"
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          label="类型名称"
          prop="categoryName"
          align="center"
          width="240"
        ></el-table-column>
        <el-table-column
          label="排序"
          align="center"
          prop="categorySort"
        ></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              size="small"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              >编辑</el-button
            >
            <el-button
              class="btn-add"
              type="text"
              icon="el-icon-plus"
              size="small"
              @click="handleAdd(scope.row)"
            >
              添加
            </el-button>
            <el-button
              size="small"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getCateList"
      />
      <!-- </el-card> -->
    </div>

    <!-- 添加或修改商品类别对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="55%">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="上级分类:" prop="parentId">
          <treeselect
            :show-count="true"
            v-model="form.parentId"
            :options="cateOptions"
            :normalizer="normalizer"
            placeholder="选择上级分类"
          />
        </el-form-item>
        <el-form-item label="分类名称:" prop="categoryName">
          <el-input
            v-model="form.categoryName"
            placeholder="请输入商品类别名称"
            style="width: 65%"
          />
        </el-form-item>
        <el-form-item label="排序" prop="categorySort">
          <el-input-number
            v-model="form.categorySort"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  certificate_add,
  certificateList,
  certificate_update,
  certificate_delete
} from "@/api/certificate/certificateAds";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "goodsCate",
  components: { Treeselect },
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryName: ""
      },
      total: 0,

      // 删除砖用
      multiple: true,
      ids: [],

      // 遮罩层
      loading: false,

      // 类别表格数据
      cateList: [],
      cateList2: [],

      // 添加商品分类表单相关项
      open: false,
      title: "",
      cateOptions: [],
      form: {},
      rules: {
        parentId: [
          { required: true, message: "商品上级分类为必选项", trigger: "blur" }
        ],
        categoryName: [
          { required: true, message: "商品类别名称不能为空", trigger: "blur" }
        ],
        categorySort: [
          { required: true, message: "商品类别顺序不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getCateList();
    this.getTreeselect();
  },
  methods: {
    querySearch(queryString, cb) {
      console.log(queryString, this.cateList2);
      var restaurants = this.cateList2;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.categoryName
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    // 查询菜单下拉树结构
    getTreeselect() {
      certificateList(this.queryParams).then(res => {
        this.cateOptions = [];
        const menu = { id: 0, categoryName: "主类目", children: [] };
        menu.children = this.handleTree(res.rows, "id");
        this.cateOptions.push(menu);
      });
    },
    // 转换菜单数据结构
    normalizer(node) {
      if (node.children == null || node.children == "null") {
        delete node.children;
      }
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.categoryName,
        children: node.children
      };
    },
    // 查询指定商品类别
    fetchGoodsType() {
      this.queryParams.pageNum = 1;
      this.getCateList();
    },
    // 查询证书类别列表
    getCateList() {
      this.loading = true;
      certificateList(this.queryParams).then(res => {
        this.loading = false;
        if (res.code == 200) {
          this.total = res.total;
          this.cateList2 = res.rows;
          this.cateList = this.handleTree(res.rows, "id");
          // this.cateList = res.rows;
        } else {
          this.msgError("查询失败！");
        }
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.getCateList();
    },

    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        categoryName: undefined,
        categorySort: null
      };
    },

    // 点击新增按钮
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row) {
        this.form.parentId = row.id;
      }
      this.open = true;
      this.title = "添加";
    },

    // 点击修改按钮
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      this.form = row;
      console.log(row);
      this.open = true;
      this.title = "修改";
    },

    // 点击提交
    submitForm() {
      this.$refs["form"].validate(valid => {
        console.log(this.form);
        if (valid) {
          if (this.form.id !== undefined) {
            certificate_update(this.form).then(res => {
              if (res.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.form = {};
                this.getCateList();
              } else {
                this.msgError(res.msg);
              }
            });
          } else {
            certificate_add(this.form).then(res => {
              if (res.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.form = {};
                this.getCateList();
              } else {
                this.msgError(res.msg);
              }
            });
          }
        }
      });
    },
    handleSelectionChange(val) {
      this.ids = val.map(item => item.id);
      this.single = val.length != 1;
      this.multiple = !val.length;
    },
    // 批量删除
    handleDelete(row) {
      console.log(row.id);
      const id = row.id || this.ids;
      this.$confirm("是否确认删除?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return certificate_delete(id);
        })
        .then(() => {
          this.getCateList();
          this.msgSuccess("删除成功");
        })
        .catch(function() {});
    }
  }
};
</script>

<style lang="scss" scoped>
.btn-add {
  margin-left: 20px;
}
</style>
